import { Injectable } from '@nestjs/common';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Album } from '../entities';
import { Transaction, TransactionRepository, Repository } from 'typeorm';
import * as _ from 'lodash';
import { UsersService } from '@/modules/users';

@Injectable()
export class AlbumsService extends TypeOrmCrudService<Album> {
  constructor(
    @InjectRepository(Album) repo,
    private readonly userService: UsersService,
  ) {
    super(repo);
  }

  async checkFav(albumId: number, userId: number) {
    const album = await this.repo.findOneOrFail(albumId, {
      relations: ['favByUsers'],
    });
    const index = album.favByUsers.findIndex(user => user.id === userId);
    return index !== -1;
  }

  @Transaction()
  async setFav(
    albumId: number,
    userId: number,
    @TransactionRepository(Album)
    albumTranRepo?: Repository<Album>,
  ) {
    const album = await albumTranRepo.findOneOrFail(albumId, {
      relations: ['favByUsers'],
    });
    const favdByUser = album.favByUsers.findIndex(user => user.id === userId);

    const data = _.pick(album, ['id', 'favByUsers', 'favCount']);

    if (favdByUser === -1) {
      const user = await this.userService.findOne(userId);
      data.favByUsers.push(user);
      data.favCount++;
      await albumTranRepo.save(data);
    }

    return _.pick(data, ['id', 'favCount']);
  }

  @Transaction()
  async removeFav(
    albumId: number,
    userId: number,
    @TransactionRepository(Album)
    albumTranRepo?: Repository<Album>,
  ) {
    const album = await albumTranRepo.findOneOrFail(albumId, {
      relations: ['favByUsers'],
    });
    const favdByUser = album.favByUsers.findIndex(user => user.id === userId);

    const data = _.pick(album, ['id', 'favByUsers', 'favCount']);

    if (favdByUser !== -1) {
      data.favByUsers.splice(favdByUser, 1);
      data.favCount--;
      await albumTranRepo.save(data);
    }

    return _.pick(data, ['id', 'favCount']);
  }
}
